package com.heima.behavior.service.impl;

import com.heima.behavior.service.ApBehaviorEntryService;
import com.heima.behavior.service.ApReadBehaviorService;
import com.heima.common.exception.CustException;
import com.heima.model.behavior.dtos.ReadBehaviorDTO;
import com.heima.model.behavior.pojos.ApBehaviorEntry;
import com.heima.model.behavior.pojos.ApReadBehavior;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.threadlocal.AppThreadLocalUtils;
import com.heima.model.user.pojos.ApUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.Date;

@Slf4j
@Service
public class ApReadBehaviorServiceImpl implements ApReadBehaviorService {
    @Autowired
    MongoTemplate mongoTemplate;
    @Autowired
    ApBehaviorEntryService behaviorEntryService;
    /**
     * 保存用户阅读数据
     * @param dto
     * @return
     */
    @Override
    public ResponseResult readBehavior(ReadBehaviorDTO dto) {
        // 检查用户是否登录
        ApUser user = AppThreadLocalUtils.getUser();
        if(user == null){
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN);
        }
        //查询行为实体
        ApBehaviorEntry behaviorEntry = behaviorEntryService.findByUserIdOrEquipmentId(user.getId(), dto.getEquipmentId());
        if (behaviorEntry==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"获取行为实体信息失败");
        }
        //查询指定文章阅读行为是否存在
        Query query = Query.query(Criteria.where("entryId").is(behaviorEntry.getId())
                .and("articleId").is(dto.getArticleId()));
        ApReadBehavior apReadBehavior = mongoTemplate.findOne(query, ApReadBehavior.class);
        if (apReadBehavior==null){
            //不存在,新增阅读数据
            apReadBehavior = new ApReadBehavior();
            apReadBehavior.setEntryId(behaviorEntry.getId());
            apReadBehavior.setArticleId(dto.getArticleId());
            apReadBehavior.setCount((short)1);
            apReadBehavior.setCreatedTime(new Date());
            apReadBehavior.setUpdatedTime(new Date());
            mongoTemplate.save(apReadBehavior);
        }else {
            //存在  更新阅读次数
            apReadBehavior.setCount((short)(apReadBehavior.getCount()+1));
            mongoTemplate.save(apReadBehavior);
        }
        return ResponseResult.okResult();
    }
}
